package com.itump.base.util;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;

/**
 *   
 * 作者：itump <br>
 * 功能描述: 文件上传/下载功能 <br>
 * 创建时间：2011-9-17 8：25 <br>
 * 版本信息：1.0 <br>
 * Copyright: Copyright (c) 2011 <br>
 * 
 */
public class FileManager {
	private FTPClient ftp = new FTPClient();

	private DataOutputStream outputs;

	private OutputStream outs;

	private String hostname = "";

	private int port = 21;

	private String uid = "";

	private String pwd = "";

	private String rootPath = "";
	
	private String webserver = "";

	private static final Log log = LogFactory.getLog(FileManager.class);

	/**
	 * constructor
	 */
	public FileManager() {
		try {
			PropertiesReader property = PropertiesReader.getIntance();
			hostname = property.getProperty("ftp.hostname");
			port = property.getInt("ftp.port").intValue();
			uid = property.getProperty("ftp.userid");
			pwd = property.getProperty("ftp.password");
			rootPath = property.getProperty("ftp.rootpath");
			webserver = property.getProperty("web.server");
		} catch (Exception e) {
			log.error("Property Read Error");
		}
		connect();
	}

	public FileManager(String hostname, int port, String uid, String pwd) {
		this.hostname = hostname;
		this.port = port;
		this.uid = uid;
		this.pwd = pwd;
		connect();
	}

	private void connect() {
		try {
			ftp.setControlEncoding("GBK");// setControlEncoding必须在connect之前
			ftp.connect(hostname, port);
			ftp.login(uid, pwd);
			ftp.setFileType(FTP.BINARY_FILE_TYPE);
		}catch (IOException e) {
			log.error("连接主机:" + hostname + "失败!请检查端口是否正确：");
		} catch (SecurityException e) {
			log.error("无权限与主机:" + hostname + "连接!请检查是否有访问权限：");
		}
	}
	
	/**
	 * 功能: 断开连接
	 */
	public void stop() {
		try {
			if (ftp != null) {
				ftp.logout();
				ftp.disconnect();
			}
		} catch (IOException e) {
			log.error("与主机" + hostname + "断开连接失败!");
		}
	}

	/**
	 * 功能: 查看目录是否存在，不存在则创建目录
	 * 
	 * @return
	 */
	public String getDirectory() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String strDate = sdf.format(new Date());
		String dir = rootPath + "/" + strDate;
		try {
			FTPFile[] superFile = ftp.listFiles(dir);
			if (superFile.length > 0) {
				return dir;
			} else {
				try {
					ftp.makeDirectory(dir);
					return dir;
				} catch (Exception e) {
					log.error("Can Not Make Dir: " + dir);
					return null;
				}
			}
		} catch (Exception e) {
			log.error("Can Not List Files: " + dir);
			return null;
		}
	}

	/**
	 * 功能: 上传文件并且覆盖同名文件
	 * 
	 * @param input
	 *            type of InputStream
	 * @param filepathname
	 *            type of String
	 * @return boolean
	 */
	public boolean uploadFile(InputStream input, String filepathname) {
		boolean result = true;
		try {
			if (ftp == null) {
				connect();
			}
			ftp.setSoTimeout(1000000);
			outs = ftp.storeFileStream(filepathname);
			outputs = new DataOutputStream(outs);
			
			// 文件大小
//			outputs.size();
			
			byte[] bytes = new byte[5120];
			int c = 0;
			while ((c = input.read(bytes)) != -1) {
				outputs.write(bytes, 0, c);
			}
			outs.close();
			outputs.close();
			input.close();
		} catch (Exception e) {
			log.error("上传" + filepathname + "文件失败!");
			log.error(e);
			result = false;
		}
		return result;
	}
	/**
	 * 功能: 在FTP上新建目录
	 * 
	 * @param dirName
	 *            type of String
	 * @return boolean
	 */
	public boolean makeDirectory(String dirName)
	{
		try {
			FTPFile[] superFile = ftp.listFiles(dirName);
			if (superFile.length > 0) {
				
			} else {
				try {
					ftp.makeDirectory(dirName);
					
				} catch (Exception e) {
					log.error("Can Not Make Dir: " + dirName);
					return false;
				}
			}
			//ftp.makeDirectory(dirName);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
		return true;
	}
	/**
	 * 功能: 在FTP上重新命名
	 * 
	 * @param dirName
	 *            type of String
	 * @return boolean
	 */
	public boolean reName(String oldName,String newName)
	{
		try {
			if (ftp == null) {
				connect();
			}
			ftp.rename(oldName,newName);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
		return true;
	}
	/**
	 * 功能: 上传文件
	 * 
	 * @param input
	 *            type of InputStream
	 * @param filepathname
	 *            type of String
	 * @param overwrite
	 *            type of boolean,是否覆盖同名文件
	 * return String
	 */
	public String uploadUniqueFile(InputStream input, String filepathname,
			boolean overwrite) {
		if (overwrite) {
			if (uploadFile(input, filepathname)) {
				return "success";
			} else {
				return "fail";
			}
		} else {
			try {
				if (ftp == null) {
					connect();
				}
				FTPFile[] files = ftp.listFiles(filepathname);
				if (files.length > 0) {
					log.error("文件名已存在：" + filepathname);
					return "exist";
				} else {
					if (uploadFile(input, filepathname)) {
						return "success";
					} else {
						return "fail";
					}
				}
			} catch (Exception e) {
				log.error("上传" + filepathname + "文件失败!");
				log.error(e);
				return "fail";
			}
		}
	}

	/**
	 * 功能: 下载文件
	 * 
	 * @param link
	 * @return
	 */
	public InputStream downloadFile(String link) {
		try {
			if (ftp == null) {
				connect();
			}
			InputStream is = ftp.retrieveFileStream(link);
			return is;
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * 删除文件
	 * 
	 * @param basePath
	 *            type of String
	 * @param filepathname
	 *            type of String
	 * @return boolean
	 */
	public boolean deleFile(String pathname) {
		try {
			return ftp.deleteFile(pathname);
		} catch (Exception e) {
			log.error("Delete File Error:" + pathname);
			return false;
		}
	}

	/**
	 * 得到目录和文件
	 * 
	 * @param fileName
	 *            type of String
	 * @return String
	 */
	public static String getPath(String fileName) {
		DateFormat basePath = new SimpleDateFormat("yyyy\\MM");
		if (fileName != null) {
			return (basePath + "\\" + fileName);
		}
		
		return "";
	}

	public String getRootPath() {
		return rootPath;
	}

	public String getWebserver() {
		return webserver;
	}

	public static void main(String args[]){
		 //从FTP文件中下载
		/**
		FileManager fileManager = null;
		String id = Utils.chgNull(request.getParameter("id"));
		Procedure procedure = new Procedure();
		ProcDownloadLog procDownloadLog = new ProcDownloadLog();
		procedure = procedureManager.getProcedureById(id);// 
		String jarPath = procedure.getJarPath();
		String procname = jarPath.substring(jarPath.lastIndexOf("/")+1); //文件名称
		fileManager = new FileManager();
		String procName = new String(procname.getBytes("gbk"), "iso8859-1");
		String contentType="applicaiton/x-msdownload";
		if(procname.indexOf(".rar")>=0 || procname.indexOf(".zip")>=0 ){
			contentType = "applicaiton/zip";
		}else if(procname.indexOf(".pdf")>=0){
			contentType = "applicaiton/pdf";
		}
		
		response.setContentType(contentType);
		response.setHeader("Content-Disposition", "attachment; filename="
				+ procName);
		response.setHeader("Pragma", "public");
		response.setHeader("Cache-Control", "max-age=30");
		InputStream in = fileManager.downloadFile(jarPath);
		Utils.copyStream(in, response.getOutputStream());
		**/
	}
}
